package org.example.ruangong.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.example.ruangong.model.Entry;
import org.example.ruangong.model.Result;
import org.example.ruangong.model.User;
import org.example.ruangong.service.EmailService;
import org.example.ruangong.service.EntryService;
import org.example.ruangong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.example.ruangong.util.JwtUtil;
import org.example.ruangong.util.ResponseUtil;

import java.util.List;
import java.util.Map;

/**
 * 功能描述：
 */
@RestController
@RequestMapping("/Entry")
public class EntryController {

    @Autowired
    private EntryService entryService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/addEntry")
    public Result addEntry(@RequestBody Entry entryDTO,
                           @RequestHeader(value = "Authorization", required = false) String token) {


        // 从token中获取用户ID
        Integer userId = jwtUtil.getUidFromToken(token);
        System.out.println(token);
        System.out.println(userId);
        if (userId == null||!userId.equals(entryDTO.getUsers())) {
            return Result.fail(400, "用户未认证或token无效", null);
        }

        if (StringUtils.isEmpty(entryDTO.getTitle()) || StringUtils.isEmpty(entryDTO.getArticle())) {
            return Result.fail(400, "标题或内容不能为空", null);
        }

        try {
            Entry entry = new Entry();
            entry.setTitle(entryDTO.getTitle());
            entry.setKeys(entryDTO.getKeys());
            entry.setArticle(entryDTO.getArticle());
            entry.setUsers(entryDTO.getUsers());
            entry.setEid(entryDTO.getEid());
            entryService.addEntry(entry);

            return Result.succ(200, "词条添加成功", null);
        } catch (Exception e) {
            return Result.fail(500, "服务器内部错误: " + e.getMessage(), null);
        }
    }

    @PutMapping("/PutEntry")
    public Result putEntry(@RequestBody Entry entryDTO,
                                        @RequestHeader(value = "Authorization", required = false) String token) {

        // 1. 从token中获取用户ID
        Integer userId = jwtUtil.getUidFromToken(token);


        if (userId == null||!userId.equals(entryDTO.getUsers())) {
            return Result.fail(400, "用户未认证或token无效", null);
        }

        // 2. 检查必填参数
        if (entryDTO.getEid() == null) {
            return Result.fail(400, "词条ID不能为空", null);
        }
        if (StringUtils.isEmpty(entryDTO.getTitle()) || StringUtils.isEmpty(entryDTO.getArticle())) {
            return Result.fail(400, "标题或内容不能为空", null);
        }

        try {
            // 3. 检查词条是否存在
            Entry existingEntry = entryService.getEntryById(entryDTO.getEid());
            if (existingEntry == null) {
                return Result.fail(10003, "词条不存在", null);
            }

            // 4. 更新词条内容
            existingEntry.setTitle(entryDTO.getTitle());
            existingEntry.setArticle(entryDTO.getArticle());
            existingEntry.setUsers(userId);
            // 5. 添加修改者到用户列表
            // 这里的entryService.updateEntry方法会处理users字段的更新
            entryService.updateEntry(existingEntry, userId);

            return Result.succ(200, "词条修改成功", null);
        } catch (Exception e) {
            return Result.fail(500, "服务器内部错误: " + e.getMessage(), null);
        }
    }
    @GetMapping("/CheckEntryByKey/{key}")
    public Result checkEntryByKey(@PathVariable String key) {
        // 1. 验证参数
        if (StringUtils.isBlank(key)) {
            return Result.fail(400, "关键词不能为空", null);
        }

        try {
            // 2. 调用服务层查询词条
            List<Entry> entries = entryService.getEntriesByKey(key);

            // 3. 处理查询结果
            if (entries == null || entries.isEmpty()) {
                return Result.fail(10003, "没有找到相关词条", null);
            }

            return Result.succ(200, "查询成功", entries);
        } catch (Exception e) {
            return Result.fail(500, "服务器内部错误: " + e.getMessage(), null);
        }
    }
    @GetMapping("/CheckEntryByUid/{uid}")
    public Map<String, Object> checkEntryByUid(@PathVariable Integer uid) {
        // 1. 验证参数
        if (uid == null) {
            return ResponseUtil.createResponse(400, null, "用户ID不能为空");
        }

        try {
            // 2. 调用服务层查询词条
            List<Entry> entries = entryService.getEntriesByUid(uid);

            // 3. 处理查询结果
            if (entries == null || entries.isEmpty()) {
                return ResponseUtil.createResponse(10003, null, "该用户没有修改过任何词条");
            }

            return ResponseUtil.createResponse(200, entries, "查询成功");
        } catch (Exception e) {
            return ResponseUtil.createResponse(500, null, "服务器内部错误: " + e.getMessage());
        }
    }

    @PostMapping("/AddKey")
    public Map<String, Object> addKey(@RequestBody Map<String, Object> requestBody,
                                      @RequestHeader(value = "Authorization", required = false) String token) {
        // 1. 从token中获取用户ID
        Integer userId = jwtUtil.getUidFromToken(token);


        // 2. 验证参数
        Integer eid = (Integer) requestBody.get("eid");
        String key = (String) requestBody.get("key");


        if (userId == null) {
            return ResponseUtil.createResponse(400, null, "用户未认证或token无效");
        }

        if (eid == null || StringUtils.isBlank(key)) {
            return ResponseUtil.createResponse(400, null, "词条ID或关键词不能为空");
        }

        try {
            // 3. 检查词条是否存在
            Entry entry = entryService.getEntryById(eid);
            if (entry == null) {
                return ResponseUtil.createResponse(10003, null, "词条不存在");
            }

            // 4. 检查关键词是否已存在
            if (entryService.keyExists(eid, key)) {
                return ResponseUtil.createResponse(601, null, "关键词已存在");
            }

            // 5. 添加关键词
            entryService.addKey(eid, key, userId,entry);

            return ResponseUtil.createResponse(200, null, "关键词添加成功");
        } catch (Exception e) {
            return ResponseUtil.createResponse(500, null, "服务器内部错误: " + e.getMessage());
        }
    }

    @DeleteMapping("/Delkey")
    public Map<String, Object> delKey(@RequestBody Map<String, Object> requestBody,
                                      @RequestHeader(value = "Authorization", required = false) String token) {
        // 1. 从token中获取用户ID
        Integer userId = jwtUtil.getUidFromToken(token);


        // 2. 验证参数
        Integer eid = (Integer) requestBody.get("eid");
        String key = (String) requestBody.get("key");

        if (userId == null) {
            return ResponseUtil.createResponse(400, null, "用户未认证或token无效");
        }

        if (eid == null || StringUtils.isBlank(key)) {
            return ResponseUtil.createResponse(400, null, "词条ID或关键词不能为空");
        }

        try {
            // 3. 检查词条是否存在
            Entry entry = entryService.getEntryById(eid);
            if (entry == null) {
                return ResponseUtil.createResponse(10003, null, "词条不存在");
            }

            // 4. 检查关键词是否存在
            if (!entryService.keyExists(eid, key)) {
                return ResponseUtil.createResponse(10003, null, "关键词不存在");
            }

            // 5. 删除关键词
            entryService.deleteKey(eid, key, userId, entry);

            return ResponseUtil.createResponse(200, null, "关键词删除成功");
        } catch (Exception e) {
            return ResponseUtil.createResponse(500, null, "服务器内部错误: " + e.getMessage());
        }
    }
}
